package com.sgai.zero_robot.ui.main;


import static com.sgai.zero_robot.ui.control.ZeroControlActivity.high;
import static com.sgai.zero_robot.ui.control.ZeroControlActivity.isShowLowBatteryHigh;
import static com.sgai.zero_robot.ui.control.ZeroControlActivity.isShowLowBatteryLow;
import static com.sgai.zero_robot.ui.control.ZeroControlActivity.low;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.sgai.zero_robot.base.BaseActivity;
import com.sgai.zero_robot.base.BaseViewModel;
import com.sgai.zero_robot.core.RobotManagerFactory;
import com.sgai.zero_robot.core.callback.BatteryCallback;
import com.sgai.zero_robot.core.callback.RobotCallback;
import com.sgai.zero_robot.databinding.ActivityMainBinding;
import com.sgai.zero_robot.ui.alarm.AlarmActivity;
import com.sgai.zero_robot.ui.config.ConfigActivity;
import com.sgai.zero_robot.ui.debug.DebugActivity;
import com.sgai.zero_robot.ui.history.ZeroHistoryActivity;
import com.sgai.zero_robot.utils.BatteryHelper;
import com.siyi.imagetransmission.config.SettingsConfig;
import com.siyi.imagetransmission.decoder.IDecodeListener;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity<ActivityMainBinding, BaseViewModel> implements View.OnClickListener {
    private Timer timer;
    private TimerTask timerTask;
    @Override
    public void initViews(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mBinding.btCheck.setOnClickListener(this);
        mBinding.btHistory.setOnClickListener(this);
        mBinding.tvDebug.setOnClickListener(this);
        mBinding.btAlarm.setOnClickListener(this);
        SettingsConfig.getInstance().initConfig(this);
        SettingsConfig.setDecodeType(this, IDecodeListener.DECODE_TYPE_HARD);
        SettingsConfig.setLogEnable(false);
        SettingsConfig.setRectify(this, true);
        BatteryHelper.getInstance().start();
    }
    private BatteryCallback batteryCallback = new BatteryCallback() {
        @Override
        public void onBattery(int battery) {
            setRobotBattery(battery);
        }

        @Override
        public void onVoltage(String voltage) {

        }

        @Override
        public void onCurrent(String current) {

        }

        @Override
        public void onHealthy(String healthy) {

        }

        @Override
        public void onCellTemperature(String temperature) {

        }

        @Override
        public void onMOSTemperature(String temperature) {

        }

        @Override
        public void onBMSSystem1(String state) {

        }

        @Override
        public void onBMSSystem2(String state) {

        }

        @Override
        public void onCellVoltage1(String voltage) {

        }

        @Override
        public void onCellVoltage2(String voltage) {

        }

        @Override
        public void onCellVoltage3(String voltage) {

        }

        @Override
        public void onCellVoltage4(String voltage) {

        }

        @Override
        public void onCount(String count) {

        }
    };
    private void setRobotBattery(int battery){
        mBinding.ivRobotBattery.setImageResource(getRBattery(battery));
        setBatteryTextColor(mBinding.tvRobotBattery, battery);
        if (high<battery&&battery<=low&&!isShowLowBatteryLow){
            showAlarm(2,"告警","电量低，请谨慎操作!",null);
            isShowLowBatteryLow = true;
            return;
        }
        if (battery<=high&&!isShowLowBatteryHigh){
            showAlarm(2,"严重告警","电量过低，请立即收回机器人!",null);
            isShowLowBatteryHigh = true;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        startTimer();
        RobotManagerFactory.getInstance().addBatteryCallback(batteryCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
        RobotManagerFactory.getInstance().removeBatteryCallback(batteryCallback);
    }

    private void startTimer() {
        stopTimer();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBinding.ivMobileBattery.setImageResource(getMBattery(BatteryHelper.getInstance().percent));
                        setBatteryTextColor(mBinding.tvMobileBattery,BatteryHelper.getInstance().percent);
                        mBinding.ivRobotBattery.setImageResource(getRBattery(RobotManagerFactory.getInstance().battery));
                        setBatteryTextColor(mBinding.tvRobotBattery, RobotManagerFactory.getInstance().battery);
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 5000);
    }

    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null) {
            timer.cancel();
            ;
            timer = null;
        }
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        if (view == mBinding.btCheck) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "申请权限", Toast.LENGTH_SHORT).show();
                // 申请 相机 麦克风权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 102);
            } else {
                if (RobotManagerFactory.getInstance().isConnect()) {
                    startActivity(new Intent(MainActivity.this, ConfigActivity.class));
                } else {
                    showToast("机器人正在连接中...");
                }
            }
        } else if (view == mBinding.btHistory) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "申请权限", Toast.LENGTH_SHORT).show();
                // 申请 相机 麦克风权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 102);
            } else {
                startActivity(new Intent(MainActivity.this, ZeroHistoryActivity.class));
            }
        } else if (view == mBinding.tvDebug) {
            startActivity(new Intent(MainActivity.this, DebugActivity.class));
        } else if (view == mBinding.btAlarm) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "申请权限", Toast.LENGTH_SHORT).show();
                // 申请 相机 麦克风权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 102);
            } else {
                startActivity(new Intent(MainActivity.this, AlarmActivity.class));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RobotManagerFactory.getInstance().close();
        BatteryHelper.getInstance().stop();
    }
}